/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import beans.exceptions.NonexistentEntityException;
import entities.Author;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entities.Book;
import java.util.ArrayList;
import java.util.Collection;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;



@ManagedBean(name="authorDao")
@ApplicationScoped
public class AuthorDAO {

    public AuthorDAO() {
        emf = Persistence.createEntityManagerFactory("BookstorePU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Author author) {
        if (author.getBooks() == null) {
            author.setBooks(new ArrayList<Book>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Book> attachedBooks = new ArrayList<Book>();
            for (Book booksBookToAttach : author.getBooks()) {
                booksBookToAttach = em.getReference(booksBookToAttach.getClass(), booksBookToAttach.getId());
                attachedBooks.add(booksBookToAttach);
            }
            author.setBooks(attachedBooks);
            em.persist(author);
            for (Book booksBook : author.getBooks()) {
                booksBook.getAuthors().add(author);
                booksBook = em.merge(booksBook);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Author author) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Author persistentAuthor = em.find(Author.class, author.getId());
            Collection<Book> booksOld = persistentAuthor.getBooks();
            Collection<Book> booksNew = author.getBooks();
            Collection<Book> attachedBooksNew = new ArrayList<Book>();
            for (Book booksNewBookToAttach : booksNew) {
                booksNewBookToAttach = em.getReference(booksNewBookToAttach.getClass(), booksNewBookToAttach.getId());
                attachedBooksNew.add(booksNewBookToAttach);
            }
            booksNew = attachedBooksNew;
            author.setBooks(booksNew);
            author = em.merge(author);
            for (Book booksOldBook : booksOld) {
                if (!booksNew.contains(booksOldBook)) {
                    booksOldBook.getAuthors().remove(author);
                    booksOldBook = em.merge(booksOldBook);
                }
            }
            for (Book booksNewBook : booksNew) {
                if (!booksOld.contains(booksNewBook)) {
                    booksNewBook.getAuthors().add(author);
                    booksNewBook = em.merge(booksNewBook);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = author.getId();
                if (findAuthor(id) == null) {
                    throw new NonexistentEntityException("The author with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Author author;
            try {
                author = em.getReference(Author.class, id);
                author.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The author with id " + id + " no longer exists.", enfe);
            }
            Collection<Book> books = author.getBooks();
            for (Book booksBook : books) {
                booksBook.getAuthors().remove(author);
                booksBook = em.merge(booksBook);
            }
            em.remove(author);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Author> getAllAuthors() {
        return getAllAuthors(true, -1, -1);
    }

    public List<Author> getAllAuthors(int maxResults, int firstResult) {
        return getAllAuthors(false, maxResults, firstResult);
    }

    private List<Author> getAllAuthors(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createNamedQuery("getAllAuthors");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Author findAuthor(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Author.class, id);
        } finally {
            em.close();
        }
    }

    public int getAuthorCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Author as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
